﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hyt.Core.Data;
using System.Linq.Expressions;
using System.Reflection;
using Hyt.Core;

namespace System.Linq
{
    public static class QueryableExtensions
    {
        public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string orderbyproperty, OrderType ordertype)
        {
            if (string.IsNullOrWhiteSpace(orderbyproperty))
            {
                DefaultOrderbyAttribute attr = typeof(T).GetCustomAttribute<DefaultOrderbyAttribute>(true);
                if (attr == null)
                {
                    return source;
                }
                orderbyproperty = attr.Property;
            }

            ParameterExpression param = Expression.Parameter(typeof(T), orderbyproperty);
            PropertyInfo pi = typeof(T).GetProperty(orderbyproperty);
            if (pi == null)
            {
                return source;
            }
            Type[] types = new Type[2];
            types[0] = typeof(T);
            types[1] = pi.PropertyType;

            string sortingDir = string.Empty;
            if (ordertype ==  OrderType.ASC)
                sortingDir = "OrderBy";
            else
                sortingDir = "OrderByDescending";
            Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, orderbyproperty), param));
            IQueryable<T> query = source.AsQueryable().Provider.CreateQuery<T>(expr);
            return query;
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="pageNumber">页码，1为第一页</param>
        /// <param name="pageSize">尺寸</param>
        /// <returns></returns>
        public static IQueryable<T> PageBy<T>(this IQueryable<T> source, int pageNumber, int pageSize)
        {
            if (pageSize <= 0) return source;
            if (pageNumber <= 1) return source.Take(pageSize);
            return source.Skip((pageNumber-1) * pageSize).Take(pageSize);
        }
    }
}
